<?php
/**
 * @Description 文件数据上传
 * @Sonkwl Xiong
 * @Date 2022/07/19 13:58:13
 */
namespace procjson;

class upfile{
    static public $path='files';
    static public $filepath='';
    /** 
     * 生成存储路径
    */
    static public function CheckDir(){
        if(!is_dir(self::$path)){
            if(!mkdir(self::$path,0777,true)){
                \procjson\http::Response(array("res"=>"NG","message"=>"创建文件目录失败"));
            }
        }
        if(!is_dir(self::$path.'/'.date("Ymd"))){
            if(!mkdir(self::$path.'/'.date("Ymd"),0777,true)){
                \procjson\http::Response(array("res"=>"NG","message"=>"创建日期目录失败"));
            }
        }
    }
    /** 
     * 处理图片数据返回文件路径
    */
    static public function Img($data){
        self::CheckDir();
        $reg = '/data:image\/(\w+?);base64,(.+)$/si';
        preg_match($reg,$data,$match_result);
        $path=self::$path.'/'.date("Ymd").'/'.date("His").random_int(1,10000).random_int(1,10000).'.jpg';//亿分之一概率相同
        // echo $path;
        try {
            file_put_contents($path,base64_decode($match_result[2]));
            return self::$filepath.$path;
        } catch (\Throwable $th) {
            \procjson\http::Response(array("res"=>"NG","message"=>"文件报错失败"));
        }
        
    }
    /**
    * 處理PDF文件並返回文件存儲路徑 
    */
    static public function Pdf($data){
        self::CheckDir();
        $reg = '/data:application\/(\w+?);base64,(.+)$/si';
        preg_match($reg,$data,$match_result);
        $path=self::$path.'/'.date("Ymd").'/'.date("His").random_int(1,10000).random_int(1,10000).'.pdf';//亿分之一概率相同
        try {
            file_put_contents($path,base64_decode($match_result[2]));
            return self::$filepath.$path;
        } catch (\Throwable $th) {
            \procjson\http::Response(array("res"=>"NG","message"=>"文件报错失败"));
        }
    }
}
?>